const express = require('express');
const router = express.Router();
const axios = require('axios');
const auth = require('../middleware/auth');
const { getHistoricalWeather } = require('../controllers/weatherController');

// Get current weather
router.get('/current/:location', auth, async (req, res) => {
  try {
    const { location } = req.params;
    
    if (!process.env.WEATHER_API_KEY) {
      return res.status(500).json({ 
        message: 'API key not configured',
        error: 'Please set WEATHER_API_KEY in your .env file'
      });
    }

    // Call OpenWeatherMap API
    const response = await axios.get('https://api.openweathermap.org/data/2.5/weather', {
      params: {
        q: location,
        appid: process.env.WEATHER_API_KEY,
        units: 'metric', // 使用摄氏度
        lang: 'zh_cn' // 使用中文
      }
    });

    res.json(response.data);
  } catch (error) {
    console.error('Weather API Error:', error.response?.data || error.message);
    res.status(500).json({ 
      message: 'Error fetching weather data',
      error: error.response?.data?.message || error.message
    });
  }
});

// Get forecast
router.get('/forecast/:location', auth, async (req, res) => {
  try {
    const { location } = req.params;
    
    if (!process.env.WEATHER_API_KEY) {
      return res.status(500).json({ 
        message: 'API key not configured',
        error: 'Please set WEATHER_API_KEY in your .env file'
      });
    }

    const response = await axios.get('https://api.openweathermap.org/data/2.5/forecast', {
      params: {
        q: location,
        appid: process.env.WEATHER_API_KEY,
        units: 'metric',
        lang: 'zh_cn',
        cnt: 40 // 5天预报，每3小时一次
      }
    });

    res.json(response.data);
  } catch (error) {
    console.error('Forecast API Error:', error.response?.data || error.message);
    res.status(500).json({ 
      message: 'Error fetching forecast data',
      error: error.response?.data?.message || error.message
    });
  }
});

// Get historical weather
router.get('/history/:location', auth, getHistoricalWeather);

module.exports = router; 